<template>
  <div>
    <div class="header_">
      <template v-for="{ name, oid } in ApplicationList">
        <div
          class="app"
          :style="{ background: appId === oid ? 'white' : '' }"
          @click="selectionApp(oid)"
          :key="oid"
        >
          {{ name }}
        </div>
      </template>
    </div>
    <div class="con_">
      <el-tabs size="mini" v-model="tabType" @tab-click="changeTab">
        <el-tab-pane label="页面" name="page"></el-tab-pane>
        <el-tab-pane label="布局" name="layout"></el-tab-pane>
      </el-tabs>
      <avue-crud
        :option="option"
        :key="`page-${tabType}`"
        v-if="tabType === 'page'"
        :table-loading="loading"
        :data="tableData"
        @selection-change="(v) => $set(this, 'selection', v)"
        ref="crud"
      >
        <template slot="menuLeft">
          <el-button
            size="small"
            type="primary"
            v-if="tabType === 'page'"
            @click="
              addToTabsList(
                '页面',
                { oid: -1, tabType: 'page' },
                'applicationManageTemp',
                'open'
              )
            "
          >
            新增
          </el-button>
          <el-button
            size="small"
            type="primary"
            v-if="tabType === 'layout'"
            @click="
              addToTabsList(
                '布局',
                { oid: -1, tabType: 'layout' },
                'applicationManageTemp',
                'open'
              )
            "
          >
            新增
          </el-button>
          <el-button
            size="small"
            :disabled="selection.length === 0"
            @click="del(selection)"
          >
            删除
          </el-button>
        </template>

        <template slot="nameCn" slot-scope="{ row }">
          <span
            class="column-btn"
            @click="
              addToTabsList(
                row.nameCn + '页面',
                { ...row, tabType: 'page' },
                'applicationManageTemp',
                'view'
              )
            "
          >
            {{ row.nameCn }}
          </span>
        </template>

        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" @click="showDesign(row)">设计</el-button>
          <!-- <el-button type="text" @click="publish(row)" > 发布 </el-button> -->
          <el-button
            type="text"
            v-if="row.state !== 1"
            @click="showPublish(row)"
          >
            发布
          </el-button>
          <el-button type="text" disabled v-else> 发布 </el-button>
        </template>
      </avue-crud>
      <avue-crud
        :option="optionLayout"
        :key="`layout-${tabType}`"
        v-if="tabType === 'layout'"
        :table-loading="loading"
        @current-change="currentChange"
        @size-change="sizeChange"
        :data="tableDataLayout"
        @selection-change="(v) => $set(this, 'selection', v)"
        ref="crud"
      >
        <template slot="menuLeft">
          <el-button
            size="small"
            type="primary"
            @click="
              addToTabsList(
                '布局',
                { oid: -1, tabType: 'layout' },
                'applicationManageTemp',
                'open'
              )
            "
          >
            新增
          </el-button>
          <el-button
            size="small"
            :disabled="selection.length === 0"
            @click="del(selection)"
          >
            删除
          </el-button>
        </template>

        <template slot="nameCn" slot-scope="{ row }">
          <span
            class="column-btn"
            @click="
              addToTabsList(
                row.nameCn + '布局',
                { ...row, tabType: 'layout' },
                'applicationManageTemp',
                'view'
              )
            "
          >
            {{ row.nameCn }}
          </span>
        </template>

        <template slot="menu" slot-scope="{ row }">
          <el-button type="text" @click="showDesign(row)">设计</el-button>
          <!-- <el-button type="text" @click="publish(row)" > 发布 </el-button> -->
          <el-button
            type="text"
            v-if="row.state !== 1"
            @click="showPublish(row)"
          >
            发布
          </el-button>
          <el-button type="text" disabled v-else> 发布 </el-button>
        </template>
      </avue-crud>
    </div>

    <ms-drawer
      key="2"
      @refresh="getPage()"
      ref="md"
      :visible.sync="visible"
      :tab-list.sync="tabsList"
    ></ms-drawer>
    <dialog-form-design
      :ROW="ROW"
      :key="ROW"
      :visible.sync="visible_design"
      @refresh="getPage()"
    ></dialog-form-design>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="visible_view"
      title="预览页面"
      width="60%"
      class="small-padding-dialog"
      :modal-append-to-body="false"
    >
      <div class="body_">
        <v-form-render
          v-if="visible_view"
          ref="render"
          :script="pScript"
          :formJson="json"
          :previewState="true"
        >
        </v-form-render>
      </div>
      <div slot="footer">
        <!-- <el-button size="medium" @click="visible_view=false">取消</el-button> -->
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="popVisible"
      width="400px"
      class="publish-padding-dialog"
      :modal-append-to-body="false"
    >
      <p>是否发布？</p>
      <div slot="footer">
        <el-button size="mini" type="text" @click="popVisible = false"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="text"
          v-if="ROW.children && ROW.children.length > 0"
          @click="publish(false)"
          >发布当前页面</el-button
        >
        <el-button size="mini" type="primary" v-else @click="publish(false)"
          >发布</el-button
        >
        <el-button
          type="primary"
          v-if="ROW.children && ROW.children.length > 0"
          size="mini"
          @click="publish(true)"
          >发布所有子页面</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as api from "@/api/applicationManage/applicationManage";
import { getApplicationList } from "@/api/applicationManage/applicationManage";
import DialogFormDesign from "@/DMDComponents/dialogFormDesign.vue";
import VFormRender from "@/components/form-render/index.vue";

export default {
  name: "applicationManage",
  components: { VFormRender, DialogFormDesign },
  data() {
    return {
      tabType: "page",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      tableData: [],
      tableDataLayout: [],
      selection: [],
      loading: false,
      option: {
        height: "auto",
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        labelWidth: 120,
        menuWidth: 100,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        rowKey: "code",
        rowParentKey: "parentCode",
        column: [
          {
            label: "页面名称",
            prop: "nameCn",
            slot: true,
          },
          //   {
          //     label: "应用名称",
          //     prop: "nameEn",
          //   },
          {
            label: "页面编码",
            prop: "code",
          },
          {
            label: "版本",
            prop: "version",
          },
          {
            label: "描述",
            prop: "describeCn",
          },
          {
            label: "状态",
            prop: "state",
            dicData: [
              {
                label: "修改中",
                value: 0,
              },
              {
                label: "已发布",
                value: 1,
              },
              {
                label: "修改中",
                value: 2,
              },
            ],
          },
          {
            label: "所有者",
            prop: "",
          },
        ],
      },
      optionLayout: {
        height: "auto",
        calcHeight: 30,
        dialogWidth: 900,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        labelWidth: 120,
        menuWidth: 100,
        viewBtn: false,
        dialogClickModal: false,
        tabs: true,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        refreshBtn: false,
        columnBtn: false,
        rowKey: "name",
        rowParentKey: "parentCode",
        column: [
          {
            label: "布局名称",
            prop: "nameCn",
            slot: true,
          },
          //   {
          //     label: "应用名称",
          //     prop: "nameEn",
          //   },
          {
            label: "布局编码",
            prop: "name",
          },
          {
            label: "版本",
            prop: "version",
          },
          {
            label: "描述",
            prop: "describeCn",
          },
          {
            label: "状态",
            prop: "state",
            dicData: [
              {
                label: "修改中",
                value: 0,
              },
              {
                label: "已发布",
                value: 1,
              },
              {
                label: "修改中",
                value: 2,
              },
            ],
          },
          {
            label: "所有者",
            prop: "",
          },
        ],
      },

      visible: false,
      popVisible: false,
      tabsList: [],
      idKey: "oid",
      ApplicationList: [],
      appId: "",
      visible_design: false,
      ROW: { children: [] },
      visible_History: false,
      tabsList_History: [],
      visible_view: false,
      json: {},
      pScript: {
        data: {},
        methods: {},
      },
    };
  },
  methods: {
    changeTab(val) {
      this.getPage();
    },
    // 获取最外层节点的oid
    getTopParentOid(row) {
      const [selected] = this.tableData.filter(
        (v) => v.code === row.topParentCode
      );
      return selected || {};
    },
    showPublish(row) {
      this.ROW = { ...row };
      this.popVisible = true;
    },
    showDesign(row) {
      this.ROW = { ...row, tabType:this.tabType,allList: this.getTopParentOid(row) };
      console.log('6666666',this.ROW)
      // this.$nextTick(() => {
      //   this.visible_design = true;
      // });
      this.visible_design = true;
    },
    view(row) {
      if (row.json && row.json.length > 0) {
        this.json = JSON.parse(row.json);
        this.initScript(this.json.pageScript);
        this.$nextTick(() => {
          this.visible_view = true;

          this.$nextTick((_) => {
            this.$refs["render"].setSubFormValues();
          });
        });
      }
    },
    initScript(s) {
      if (s.data) {
        this.pScript.data = JSON.parse(s.data);
      }

      if (s.methods) {
        s.methods.forEach((item) => {
          let obj = {};
          obj[item.funName] = new Function("arguments", item.funBody);
          Object.assign(this.pScript.methods, obj);
        });
      }
    },

    publish(isAll) {
      this.popVisible = false;
      let method = this.tabType === "page" ? "publish" : "publishLayout";
      const paramsData = this.tabType === "page" ? { id: this.ROW.oid, pub: isAll }:{ oid: this.ROW.oid, pub: isAll }
      api[method](paramsData).then((res) => {
        if (res.data.success) {
          this.$message.success("发布成功");
        } else {
          this.$message.error(res.data.msg);
        }
        this.getPage();
        this.selection = [];
      });
    },
    del(data) {
      let ids = data.map((i) => i.oid).join(",");
      let method = this.tabType === "page" ? "del" : "delLayout";
      this.$confirm("是否删除").then(() => {
        api[method]({ ids: ids }).then(() => {
          this.$message.success("删除成功");
          this.getPage();
          this.selection = [];
        });
      });
    },
    selectionApp(oid) {
      this.appId = oid;
      let event = new CustomEvent("ApplicationId", { detail: oid });
      document.dispatchEvent(event);
      this.getPage();
    },
    getPage() {
      if (this.tabType === "page") {
        api.pageTree({ applicationId: this.appId }).then((res) => {
          this.tableData = res.data.data;
          this.loading = false;
        });
      } else {
        const { current, size } = this.page;
        api.layoutPage(current, size, {applicationId:this.appId}).then((res) => {
          this.tableDataLayout = res.data.data.list;
        });
      }
    },
    // 向抽屉中添加tab页 根据 oid 去重
    addToTabsList(title, row, component, type) {
      let ids = this.tabsList.map(
        (item) => item.row[this.idKey] + "-" + item.component
      );
      if (!ids.includes(row[this.idKey] + "-" + component)) {
        this.tabsList.push({ title, row, component, type });
      }

      this.visible = true;

      this.$nextTick(() => {
        this.selectionApp(this.appId);
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.getPage();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.getPage();
    },
  },
  mounted() {
    getApplicationList().then((res) => {
      this.ApplicationList = res.data.data;
      this.selectionApp(res.data.data[0].oid);
    });
    this.$nextTick(() => {
      // 表格错位解决方法
      this.$refs.crud.refreshTable();
    });
  },
};
</script>
<style lang="scss" scoped>
$Header_height: 60px;
.header_ {
  height: $Header_height;
  width: 100%;
  background: #f2f2f2;
  display: flex;
  flex-direction: row;
  justify-content: start;
  flex-wrap: nowrap;
  box-sizing: border-box;
  padding: 0 10px;

  .app {
    padding: 0 10px;
    margin: 15px 5px;
    line-height: 30px;
    height: 30px;
    border-radius: 5px;
    cursor: pointer;
  }
}

.con_ {
  height: calc(100% - #{$Header_height} - 10px);
  width: 100%;
  margin-top: 10px;
}
.publish-padding-dialog {
  ::v-deep .el-dialog__header {
    padding: 0;
  }
}

.small-padding-dialog {
  background-color: rgba(0, 0, 0, 0.9);
  ::v-deep .el-dialog__header {
    //padding-top: 3px;
    //padding-bottom: 3px;
    background: #f1f2f3;
    border-bottom: 1px solid #ccc;
    text-align: left;
  }

  ::v-deep .el-dialog__body {
    padding: 12px 15px 12px 15px;

    .el-alert.alert-padding {
      padding: 0 10px;
    }
  }

  ::v-deep .ace-container {
    border: 1px solid #dcdfe6;
  }
}
</style>
